import hashlib
import http.client
import random
from urllib import parse

from config import db_claim_dev, logger

appid = '20180305000131535'
secretKey = 'x1R0Y0pk9tljT7AwxQFE'


def translate(q, fromLang, toLang):
    assert fromLang in ['zh', 'en']
    assert toLang in ['zh', 'en']

    try:
        if fromLang == 'zh':
            sql = '''SELECT en_word FROM TRANSLATE WHERE zh_word = '{}' '''.format(q)
            res = db_claim_dev.getOne(sql)
            if res:
                logger.info("using cache translate {}->{}".format(q, res['en_word']))
                return res['en_word']
        else:
            sql = '''SELECT zh_word FROM TRANSLATE WHERE en_word = '{}' '''.format(q)
            res = db_claim_dev.getOne(sql)
            if res:
                logger.info("using cache translate {}->{}".format(q, res['zh_word']))
                return res['zh_word']
    except:
        pass

    res = []

    salt = random.randint(32768, 65536)
    sign = appid + q + str(salt) + secretKey
    m1 = hashlib.md5()
    m1.update(sign.encode(encoding='utf-8'))
    sign = m1.hexdigest()
    myurl = '/api/trans/vip/translate' + '?appid=' + appid + '&q=' + parse.quote(
        q) + '&from=' + fromLang + '&to=' + toLang + '&salt=' + str(salt) + '&sign=' + sign
    http_client = None

    try:
        http_client = http.client.HTTPConnection('api.fanyi.baidu.com')
        http_client.request('GET', myurl)
        response = http_client.getresponse()
        s = response.read().decode('utf-8')
        s = eval(s)
        for line in s['trans_result']:
            res.append(line['dst'])
    except Exception as e:
        # print("translate error:", s)
        pass
    finally:
        if http_client:
            http_client.close()
    res = "\n".join(res)

    if res:
        pair = (q, res) if fromLang == 'zh' else (res, q)
        pair = (pair[0].lower(), pair[1].lower())
        try:
            sql = '''INSERT INTO TRANSLATE (zh_word, en_word)
                               VALUES
                               (%s, %s)'''
            logger.info(sql)
            db_claim_dev.insert(sql, param=pair)
            db_claim_dev.end("commit")
        except:
            pass

    return res


# def translate(query_string, fromLang, toLang, to_str=True):
#     '''
#     translate(query_string="miss you", fromLang="en", toLang="zh")
#     想念你
#     translate(query_string="miss you\nlove you", fromLang="en", toLang="zh")
#     '想念你\n爱你'
#     '''
#     headers = {"User-Agent": "Mozilla/5.0 (Linux; Android 5.1.1; Nexus 6 Build/LYZ28E) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Mobile Safari/537.36"}
#     post_data = {
#         "query": query_string,
#         "from": fromLang,
#         "to": toLang,
#     }
#     post_url = "http://fanyi.baidu.com/basetrans"
#     r = requests.post(post_url, data=post_data, headers=headers) # 所有requests操作都要进行错误处理呀
#     s = json.loads(r.content.decode())
#     res = []
#     for line in s['trans']:
#         res.append(line['dst'])
#     if to_str:
#         res = "\n".join(res)
#     return res


def translate_en(q):
    return translate(q, fromLang='en', toLang='zh')


def translate_zh(q):
    return translate(q, fromLang='zh', toLang='en')


if __name__ == "__main__":
    # for _ in range(10):
    #     q = '苹果是一家很棒的公司\n我爱北京天安门'
    #     print(translate(q, fromLang='zh', toLang='en'))
    #
    #     q = 'I love python'
    #     print(translate(q, fromLang='en', toLang='zh'))

    print(translate_en('test'))
